// 引入接口文件
import { queryInfo,getProjectList,submit,showUse,queryAllAddress,getmMethod,verifyCodeFun } from './taskAddServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config'

// 初始默认状态
const defultState = {
  teamModal: {
    btnLoading: false,
  },
  loading: false,
  actionType: 'add',
  Mapmodel: false,//地图弹出框
  areaList: [],
  products: [],
  mapList: [],
  memberList: [],
  list: [],
  userList: [],
  methodList: [],
  query: {
    areaId: '',//区域id
    projectId: '',//项目id
    projectName: '',//项目名称
    taskName: '',//任务名
    startTime: '',//开始时间
    endTime: '',//结束时间
    addressName: '',//地址名称
    target: '',//拓客量
    createrName: localStorage.getItem("username"),//发布人名称
    createrId: '', //发布人
    method: '', //拓客方式
    involveUserIds: [],//人员列表
    latAndLon: [] //经纬度
  },
  suitableDataList: [],
  selectedRowKeys: [],
  selectedRows: [],
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({type: 'updateStore', payload: cloneDeep(defultState)})
          dispatch({type: 'verifyCodeFun',payload: {query}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: { 
    *verifyCodeFun({payload},{put,select,call}){
      if(yield call(verifyCodeFun,{})){
        // 执行业务操作
        if(payload.query.actionType == 'edit'){
          yield put({type: 'queryInfo',payload: payload}) // end dispatch
        }
        yield put({type: 'getProjectList', payload: {}})
        // dispatch({type: 'showUse', payload: {}})
        yield put({type: 'getAreaList', payload: {} });
      }
    },
    // 查询记录
    *queryInfo({payload}, {put, select, call}){
      let {query,memberList} = yield select(state => state[tmpModule.namespace])
      let params = { "id":payload.query.id }
      if(yield call(verifyCodeFun,{})){
      const { success, msg, zituoTask ,zituoTaskUserList } = yield call(queryInfo, {...params})
      if(success){
        // yield put({type: 'getLocalTime',payload: {}})
        query = zituoTask 
        query.target = zituoTask.target + ''
        query['latAndLon'] = []
        query.latAndLon.push(zituoTask.addressLat)
        query.latAndLon.push(zituoTask.addressLon)
        memberList = zituoTaskUserList
        yield put({
          type: 'updateStore',
          payload: {query,memberList}
        })
        yield put({ type: 'getProjectList', payload: { areaId: query.areaId } });
        yield put({type: 'getmMethod', payload: {value:query.areaId}})
        yield put({type: 'showUse', payload: {value:query.projectId}})
      }
    }
    },
    // 获取成员
    *showUse({payload}, {put, select, call}){
      let {userList} = yield select(state => state[tmpModule.namespace])
      let params = {
        projectId: payload.value,
        // channel: "行销自拓"
      }
      const { success, msg,rows } = yield call(showUse, {...params})
      if(success){
        userList = rows
        yield put({
          type: 'updateStore',
          payload: {userList}
        })
      }
    },
    *getmMethod({payload},{put,select,call}){
      let {methodList} = yield select(state => state[tmpModule.namespace])
      let params = {
        areaId : payload.value
      }
      const { success,rows } = yield call(getmMethod,params)
      if(success){
        methodList = rows.map((item,index)=>{
          return {
            label: item.methodName,
            value: item.methodId
          }
        })
        yield put({type: 'updateStore', payload: {methodList}})
      }
    },
    // 获取地图
    *getAreaList({ payload }, { put, call, select }) {
      let {mapList} = yield select(state => state[tmpModule.namespace])
      const data = yield call(queryAllAddress, {})
      if (data.success) {
        // let mapList = []
        //澳门与北京只有两级
        let arr = [data.data[0]]
        let attr = [data.data[data.data.length - 1]]
        data.data[0] = {
          label: "北京",
          value: "110100",
          children: arr
        }
        data.data[data.data.length - 1] = {
          label: "澳门",
          value: "820000",
          children: attr
        }
        mapList = data.data
        

        yield put({ type: 'updateStore', payload: { mapList } });
      }
    },
    //获取区域项目
    *getProjectList({payload},{put,select,call}){
      let {areaList} = yield select(state => state[tmpModule.namespace])
      let params = {
          level : 2,
        }
      const { data } = yield call(getProjectList, {...params})
        let list = data
        if(list.length){
        areaList =  list.map((item,index)=>{
          return {
            label: item.buname,
            value: item.buguid,
            children: item.childSysUninessunitList
          }
        })
        yield put({type: 'updateStore', payload: {areaList}})
      }
      if(payload.areaId){
        yield put({type: 'filterProjectList', payload: {areaId:payload.areaId}})
      }
    },
    *submit({payload,callback},{put,select,call}){
      let {query,memberList} = yield select(state => state[tmpModule.namespace])
      let arr = []
      let params = query
      for(var item of memberList){
        arr.push(item.id)
      }
      params.involveUserIds = arr.join(',')
      params.latAndLon = typeof(params.latAndLon) == "string"?params.latAndLon:params.latAndLon.join(',')
      const { success, msg, data } = yield call(submit, {...params})
      if(success){
        message.success('新增成功')
        callback(); // 返回结果
      }
    },
    *selectedKeysChange ({payload}, {put, select, call}) {
      let {selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
      selectedRowKeys=payload.selectedRowKeys
      selectedRows=payload.selectedRows
      yield put({
        type: 'updateStore',
        payload: {
          selectedRowKeys,selectedRows
        }
      })
    },
    *updateModel({ payload }, { put, select }) {
      yield put({ type: 'updateStore', payload });
    },
    *filterProjectList({payload},{put,select,call}){    
      let {products,areaList,selectData} = yield select(state => state[tmpModule.namespace])
      let list = []
      for(var item of areaList){
        if(item.value == payload.areaId){
          list = item.children
        }
      }
      if(list.length){
        products =  list.map((item,index)=>{
          return {
            label: item.buname,
            value: item.buguid,
          }
        })
      }
      yield put({type: 'updateStore', payload: {products}})
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
